import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../system/fontsize_provider.dart';
import '../../services/api_service.dart';
import '../../services/auth_service.dart';
import '../../utils/message_box.dart';

class PickingDetailScreen extends StatefulWidget {
  final Map<String, dynamic> jsonData;
  const PickingDetailScreen({super.key, required this.jsonData});

  @override
  _PickingDetailScreenState createState() => _PickingDetailScreenState();
}

class _PickingDetailScreenState extends State<PickingDetailScreen> {
  List<Map<String, dynamic>> _availablePOList = [];
  Map<String, dynamic>? _selectedPO;

  Map<String, dynamic> orderDetails = {
    'Order': '',
    'Wave': '',
    'Detail': '',
    'Task': '',
    'Item Number': '',
    'Location': '',
    'LPN/BIN': '',
    'Quantity': '',
  };
  
  double baseFontSize = 13;
  double listFontSize = 12;
  late double _fontScale;
  late int waveId;
  int? warehouseId;
  dynamic allPO;  // 接口返回数据可能为List或Map
  String? sourceScreen;
  late int remainingTasks = 0;

  @override
  void initState() {
    super.initState();
    waveId = widget.jsonData['waveId'];
    sourceScreen = widget.jsonData['source'];
    _getWarehouseId().then((_) {
      if (warehouseId != null) {
        getPickDetail();
      } else {
        MessageBox.showMessageBox(context, 'Missing warehouse Id.', isError: true);
      }
    });
  }

  Future<void> _getWarehouseId() async {
    final user = Provider.of<AuthService>(context, listen: false).currentUser;
    if (user?.warehouse != null) {
      setState(() {
        warehouseId = user?.warehouse;
      });
    }
  }

  Future<void> getPickDetail() async {
    if (warehouseId == null) {
      MessageBox.showMessageBox(context, 'Warehouse ID is missing', isError: true);
      return;
    }

    final apiUrl = '${ApiService.baseURL}${ApiService.getPickDetail}$waveId';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null || accessToken.isEmpty) {
      MessageBox.showMessageBox(context, 'Authentication failed', isError: true);
      return;
    }

    try {
      final response = await http.get(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
      );

      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
        print('pickingDetail----$jsonData');
        if (jsonData['code'] == 2000) {
          setState(() {
            remainingTasks = jsonData['data']['remaining_tasks']??0;
            allPO = jsonData['data']['pick_tasks'];
            List<dynamic> poList = [];
            
            // 处理接口返回可能是List或Map的情况
            if (allPO is List) {
              poList = allPO;
            } 
            _availablePOList = poList.map((po) => {
              'id': po['id'] ?? '',
              'order_number': po['order_number'] ?? 'N/A',
              'wave': po['pickwave_name'] ?? 'N/A',
              'detail': po['item_name'] ?? 'N/A',
              'task': po['task'] ?? 'N/A',
              'item_number': po['item_number'] ?? 'N/A',
              'location': po['location'] ?? 'N/A',
              'lpn': po['lpn'] ?? 'N/A',
              'status': po['status'] ?? 'N/A',
              'required_quantity': po['required_quantity'] ?? 0,
              'task_number': po['task_number'] ?? 0,
              'total_tasks': jsonData['data']['total_tasks'] ?? 0,
            }).toList();

          });
        } else {
          MessageBox.showMessageBox(context, jsonData['msg'], isError: true);
        }
      } else if (response.statusCode == 401) {
        AuthService().logout(context);
        MessageBox.showMessageBox(context, 'Session expired, please log in again.', isError: true);
      } else {
        MessageBox.showMessageBox(context, 'Server error: ${response.statusCode}', isError: true);
      }
    } catch (e) {
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  Future<void>  _finish() async{
    try{
      if(remainingTasks > 0){
        throw('Remaining $remainingTasks pick tasks, please picking first.');
      }
      if (_availablePOList.isEmpty) {
        throw('No PO data available for finish operation');
      }
      final finishData = await finishPicking();
      if(finishData != null && finishData['code'] == 2000){
        MessageBox.showMessageBox(context, finishData['msg'] );
        // 重新拉取数据刷新页面，避免类型问题
        setState(() {
          _selectedPO = null;
          _resetOrderDetails();
        });
        if(remainingTasks == 0){
          Navigator.pushNamed(
            context,
            '/outbound/single-picking',
            arguments: {
              'waveId': waveId
            }
          );
        }
        else{
          Navigator.pushNamed(
            context,
            '/picking/picking',
            arguments: {
              'waveId': waveId,
              'source': sourceScreen
            } 
          );
        }
      }
      else{
        throw(finishData!['msg']);
      }
    }catch(e){
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  Future<Map<String, dynamic>?> finishPicking() async {
    if (warehouseId == null) {
      throw('Warehouse ID is missing');
    }

    final apiUrl = '${ApiService.baseURL}${ApiService.finishPicking}';
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;

    if (accessToken == null || accessToken.isEmpty) {
      throw('Authentication failed');
    }

    try {
      final requestBody = {
        'pickwave': waveId
      };
      
      final response = await http.post(
        Uri.parse(apiUrl),
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );

      print('apiUrl-----$apiUrl');
      print('requestBody-----$requestBody');
      if (response.statusCode == 200) {
        final jsonData = json.decode(utf8.decode(response.bodyBytes)) as Map<String, dynamic>;
        print('jsonData-----$jsonData');
        if (jsonData['code'] == 2000) {
          return jsonData;
        } else {
          throw(jsonData['msg'] ?? 'Finish API returned error');
        }
      } else if (response.statusCode == 401) {
        AuthService().logout(context);
        throw('Session expired, please log in again.');
      } else {
        throw('Server error: ${response.statusCode} (Finish API)');
      }
    } catch (e) {
      throw(e.toString());
    }
  }

  Future<void> _rollback() async{
    try{
      if (_selectedPO == null) {
        throw('No PO selected for rollback');
      }
      final rollbackData = await callRollbackApi();
      if(rollbackData['code'] == 2000){
        await showDialog(
          context: context,
          barrierDismissible: false,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text(
                'Success',
                style: TextStyle(fontWeight: FontWeight.bold,fontSize: 18 * _fontScale, color:Color.fromARGB(255, 4, 170, 10)),
              ),
              content: SingleChildScrollView(
                child: ListBody(
                  children: <Widget>[
                    Text(rollbackData['msg']), // 显示纯净的错误信息
                  ],
                ),
              ),
              actions: <Widget>[
                TextButton(
                  child: const Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop(); // 关闭弹窗
                  },
                ),
              ],
            );
          },
        );
        Navigator.pushNamed(
          context,
          '/picking/picking',
          arguments: {
            'waveId': waveId,
            'source': sourceScreen
          },
        );
      }
      else{
        MessageBox.showMessageBox(context, rollbackData['msg'] ?? 'Rollback failed', isError: true);
      }
    }catch(e){
      MessageBox.showMessageBox(context, e.toString(), isError: true);
    }
  }

  Future<Map<String,dynamic>> callRollbackApi() async {
    final authService = Provider.of<AuthService>(context, listen: false);
    final accessToken = authService.accessToken;
    if (accessToken == null || accessToken.isEmpty) {
      throw('Authentication failed (Rollback)');
    }
    if (warehouseId == null) {
      throw('Warehouse ID is missing (Rollback)');
    }
    if (_selectedPO == null) {
      throw('No PO selected');
    }

    final apiUrl = ApiService.baseURL + ApiService.rollbackPicking;
    final url = Uri.parse(apiUrl);
    final requestBody = {
        'id': _selectedPO!['id']
      };
    try {
      final response = await http.post(
        url,
        headers: {
          'Authorization': 'JWT $accessToken',
          'x-warehouse-id': '$warehouseId',
          'x-timezone': 'America/Los_Angeles',
          'Content-Type': 'application/json',
          'X-Client-Type': 'app'
        },
        body: jsonEncode(requestBody),
      );

      if (response.statusCode == 200) {
        String responseBody = utf8.decode(response.bodyBytes);
        Map<String, dynamic> jsonData = json.decode(responseBody);
        print('url------$url');
        print('requestBody------$requestBody');
        print('jsondata------$jsonData');
        if (jsonData['code'] != 2000) {
          throw(jsonData['msg']);
        }
        return jsonData;
      } else {
        throw('Server error: ${response.statusCode} (Rollback API)');
      }
    } catch (e) {
      throw(e.toString());
    }
  }

  void _handleLpnSelection(Map<String, dynamic> selectedPO) {
    setState(() {
      if (_selectedPO?['id'] == selectedPO['id']) {
        _selectedPO = null;
        _resetOrderDetails();
      } else {
        _selectedPO = selectedPO;
        _updateOrderDetails(selectedPO);
      }
    });
  }

  // 【删除】冗余的文本拼接方法，改用布局组件展示字段
  // String _getPODisplayText(Map<String, dynamic> po) {
  //   return '${po['order_number']} | ${po['item_number']} | ${po['location']} | ${po['required_quantity']}';
  // }

  void _updateOrderDetails(Map<String, dynamic> po) {
    orderDetails['Order'] = po['order_number'] ?? 'N/A';
    orderDetails['Wave'] = po['wave'] ?? 'N/A';
    orderDetails['Detail'] = po['detail'] ?? 'N/A';
    orderDetails['Task'] = '${po['task_number']} / ${po['total_tasks']}' ?? 'N/A / N/A';
    orderDetails['Item Number'] = po['item_number'] ?? 'N/A';
    orderDetails['Location'] = po['location'] ?? 'N/A';
    orderDetails['LPN/BIN'] = po['lpn'] ?? 'N/A';
    orderDetails['Quantity'] = po['required_quantity'].toString() ?? 'N/A';
  }

  void _resetOrderDetails() {
    orderDetails['Order'] = '';
    orderDetails['Wave'] = '';
    orderDetails['Detail'] = '';
    orderDetails['Task'] = '';
    orderDetails['Item Number'] = '';
    orderDetails['Location'] = '';
    orderDetails['LPN/BIN'] = '';
    orderDetails['Quantity'] = '';
  }

  @override
  Widget build(BuildContext context) {
    _fontScale = Provider.of<FontSizeProvider>(context).fontScale;

    return Scaffold(
      appBar: AppBar(
        title: Text('Picking Detail', style: TextStyle(fontSize: 18 * _fontScale)),
        automaticallyImplyLeading: false,
        leading: IconButton(
          icon: const Icon(Icons.arrow_back, color: Colors.white),
          onPressed: () => 
                    Navigator.pushNamed(
                      context,
                      '/picking/picking',
                      arguments: {
                        'waveId': waveId,
                        'source': sourceScreen
                      },
                    ),
        ),
        actions: [
          IconButton(
            icon: const Icon(Icons.home, color: Colors.white),
            onPressed: () => Navigator.pushNamed(context, '/home'),
          ),
        ],
        backgroundColor: const Color(0xFF008363)
      ),
      body: GestureDetector(
        onTap: () => FocusScope.of(context).unfocus(),
        behavior: HitTestBehavior.opaque,
        child: Column(
          children: [
            Expanded(
              child: SingleChildScrollView(
                padding: const EdgeInsets.all(32),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.stretch,
                  children: [            
                    Text(
                      'PO Details:', // 【优化】标题更简洁，与卡片内容匹配
                      style: TextStyle(
                        fontSize: baseFontSize * _fontScale,
                        fontWeight: FontWeight.bold
                      ),
                    ),
                    
                    const SizedBox(height: 8),
                    Container(
                      height: 180,
                      decoration: BoxDecoration(
                        border: Border.all(color: Colors.grey, width: 1.0),
                        borderRadius: BorderRadius.circular(4.0),
                      ),
                      child: ClipRRect(
                        borderRadius: BorderRadius.circular(4.0),
                        // 【删除】冗余的ClipRect和OverflowBox，直接用ListView.builder
                        child: _availablePOList.isEmpty
                            ? Center(child: Text('No data found.', style: TextStyle(fontSize: 13 * _fontScale)))
                            : ListView.builder(
                                physics: const ClampingScrollPhysics(),
                                itemCount: _availablePOList.length,
                                itemBuilder: (context, index) {
                                  final po = _availablePOList[index];
                                  final isSelected = _selectedPO?['id'] == po['id'];
                                  
                                  // 【核心修改】卡片式列表项，对齐SearchDetaiScreen样式
                                  return InkWell(
                                    onTap: () => _handleLpnSelection(po), // 保留原有选中逻辑
                                    child: Container(
                                      margin: const EdgeInsets.symmetric(vertical: 2), // 卡片垂直间距
                                      decoration: BoxDecoration(
                                        border: Border.all(color: const Color.fromARGB(255, 169, 168, 168), width: 0.5), // 内边框
                                        borderRadius: BorderRadius.circular(4.0), // 圆角
                                        color: isSelected ? Colors.green[50] : null, // 选中背景色
                                      ),
                                      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), // 卡片内边距
                                      child: Column(
                                        crossAxisAlignment: CrossAxisAlignment.start,
                                        children: [
                                          Row(
                                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                            children: [
                                              Text(
                                                '${po['item_number'] ?? 'N/A'}',
                                                style: TextStyle(
                                                  fontSize: listFontSize * _fontScale,
                                                  fontWeight: FontWeight.bold,
                                                  color: isSelected ? Colors.green : Colors.black,
                                                ),
                                              ),
                                              Expanded(
                                                child: Padding(
                                                  padding: const EdgeInsets.only(left: 12),
                                                  child: Row(
                                                    mainAxisAlignment: MainAxisAlignment.center,
                                                    children: [
                                                      Text('SO: ', style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),),
                                                      Text(
                                                        '${po['order_number'] ?? 'N/A'}',
                                                        style: TextStyle(
                                                          fontSize: listFontSize * _fontScale,
                                                          color: isSelected ? Colors.green : Colors.black87,
                                                          fontWeight: FontWeight.bold,
                                                        ),
                                                      ),
                                                    ],
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          const SizedBox(height: 6),
                                          // 底部：横排辅助字段（Location/Qty/Status）
                                          Row(
                                            children: [
                                              // Location字段
                                              Expanded(
                                                flex: 1,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Location: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${po['location'] ?? 'N/A'}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              // Qty字段
                                              Expanded(
                                                flex: 1,
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Qty: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${po['required_quantity'] ?? 0}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                              // Status字段
                                              Expanded(
                                                child: Row(
                                                  mainAxisSize: MainAxisSize.min,
                                                  children: [
                                                    Text(
                                                      'Status: ',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                      ),
                                                    ),
                                                    Text(
                                                      '${po['status'] ?? 'N/A'}',
                                                      style: TextStyle(
                                                        fontSize: listFontSize * _fontScale,
                                                        color: isSelected ? Colors.green : Colors.black87,
                                                        fontWeight: FontWeight.bold,
                                                      ),
                                                    ),
                                                  ],
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                  );
                                },
                              ),
                      ),
                    ),
                    
                    ..._buildOrderDetails(),
                    
                    const SizedBox(height: 20),
                  ],
                ),
              ),
            ),
            
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 32, vertical: 8),
              child: Column(
                children: [
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Finish',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16 * _fontScale,
                          color: Colors.white
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: _finish,
                    ),
                  ),
                  const SizedBox(height: 3),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Rollback',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16 * _fontScale,
                          color: Colors.white
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: const Color(0xFF008363),
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: _selectedPO != null ? _rollback : null,
                    ),
                  ),
                  const SizedBox(height: 3),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      label: Text(
                        'Exception',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 16 * _fontScale,
                          color: Colors.white
                        ),
                      ),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        padding: const EdgeInsets.symmetric(vertical: 1),
                      ),
                      onPressed: () {},
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  List<Widget> _buildOrderDetails() {
    bool startRed = false;
    return orderDetails.entries.map((entry) {
      if (entry.key == 'Item Number') {
        startRed = true;
      }
      Color valueColor = startRed ? Colors.red : Colors.black87;
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 4),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            SizedBox(
              width: 150,
              child: Text(
                '${entry.key}:',
                style: TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: baseFontSize * _fontScale
                ),
              ),
            ),
            const SizedBox(width: 10),
            Expanded(
              child: Text(
                entry.value,
                style: TextStyle(
                  fontSize: baseFontSize * _fontScale,
                  fontWeight: FontWeight.bold,
                  color: valueColor,
                ),
              ),
            ),
          ],
        ),
      );
    }).toList();
  }
}